const {
	userMenu,
} = require('./config-menu')
const init = {
	'main-user': require('@modules/user/init-user'),
	'main-team': require('@modules/team/init-team'),
	'main-project': require('@modules/project/init-project'),
	'main-template': require('@modules/template/init-template'),
	'main-info': require('@modules/info/init-info'),
	'main-bug': require('@modules/bug/init-bug'),
}
const defaultNodeId = 'main-project'

module.exports = function(node) {
	let {
		mainComp,
	} = $['components-jq']
	let tabsJQ = mainComp.tabsJQ = $("#main-tabs")
	tabsJQ.tabs({
		fit: true,
		onAdd(title, index) {
			let id = tabsJQ.tabs('getTab', title)[0].id
			if (typeof init[id] == 'function') {
				init[id]()
			}
		},

		onBeforeClose(title, index) {
			let id = tabsJQ.tabs('getTab', title)[0].id
			let moduleComp = $['components-jq'][`${id.replace('main-', '')}Comp`]
			if (!moduleComp)
				return true
			let {
				dailogComp,
				components,
			} = moduleComp
			if (!dailogComp)
				return true
			let dailogArr = Object.keys(dailogComp)
			for (let i = 0; i < dailogArr.length; i++) {
				let comp = dailogComp[dailogArr[i]]
				let parent = comp.parent()
				parent.next('.window-shadow').remove()
				parent.next('.window-mask').remove();
				comp.dialog('destroy', true)
			}
			if (!components)
				return true
			let componentArr = Object.keys(components)
			for (let i = 0; i < componentArr.length; i++) {
				let comp = components[componentArr[i]]
				comp.remove()
			}
		},
	});
	initTabs(tabsJQ).then(result => {
		tabsJQ.tabs('select', 0)
	});
}

async function initTabs(tabsJQ) {
	let node = null
	for (let i = 0; i < userMenu.length; i++) {
		let menuNode = userMenu[i]
		if (defaultNodeId == menuNode.id) {
			node = menuNode
			break;
		}
	}
	let {
		title,
		content,
	} = node.attributes
	if (typeof content == 'function') {
		content = await content()
	}
	tabsJQ.tabs('add', {
		id: node.id,
		title: title,
		content,
		// closable: true,
	})
}